package kitwee.com.kanpad.orderDetail;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.kitwee.serialport.callback.SerialPortCallback;
import com.kitwee.serialport.data.model.SerialPortData;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import kitwee.com.kanpad.BaseFragment;
import kitwee.com.kanpad.BuildConfig;
import kitwee.com.kanpad.R;
import kitwee.com.kanpad.bean.RealTimeData;
import kitwee.com.kanpad.bean.SerialPortAdapter;
import kitwee.com.kanpad.bean.SocketEvent;
import okhttp3.Call;
import utils.OnMultipleClickListener;
import utils.SPUtils;

/**
 * @author GanQuan
 * @date 2018/1/22
 */

public class RealTimeDataFragment extends BaseFragment {

    @BindView(R.id.data)
    RecyclerView data;
    @BindView(R.id.btn_real_data)
    TextView btnRealData;
    @BindView(R.id.tv_nodata)
    TextView tvNodata;
    //    @BindView(R.id.received_data)
//    TextView receivedData;
//    private RealTimeAdapter realTimeAdapter;
    private SerialPortAdapter realTimeAdapter;
    private String endpoint;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.real_time_layout, container, false);
        // 连续点击3次打开串口配置页面
        layout.findViewById(R.id.btn_real_data).setOnClickListener(new OnMultipleClickListener(3) {
            @Override
            public void onMultipleClick(View v) {
                SerialPortActivity.start(getActivity());
            }
        });
        ButterKnife.bind(this, layout);
        endpoint = BuildConfig.API_ENDPOINT;
        realTimeBeanList = new ArrayList<>();

        data.setLayoutManager(new LinearLayoutManager(getActivity()));
        realTimeAdapter = new SerialPortAdapter(getActivity());
        data.setAdapter(realTimeAdapter);
        return layout;
    }

    public static String equipmentID;

    public void setEquipmentID(String id) {
        equipmentID = id;
    }

    public static RealTimeDataFragment newInstance() {
        return new RealTimeDataFragment();
    }

    //    private List<RealTimeData.DataBean> realTimeBeanList;
    private List<SerialPortDataModel> realTimeBeanList;


    @Override
    public void onStop() {
        super.onStop();
        SerialPortHelper.getInstance(getActivity()).removeCallback(mDataCallback);
    }

    @Override
    public void onStart() {
        super.onStart();
        SerialPortHelper.getInstance(getActivity()).addCallback(mDataCallback);
//        EventBus.getDefault().register(this);
    }

    private SerialPortCallback mDataCallback = new SerialPortCallback() {
        @Override
        public void onSuccess(SerialPortData data) {
            LogUtils.e(data.getFlag() + " , " + data.getData() + "\n");
//
//            List<Pair<String,String>> pairs = new ArrayList<>();
//            JSONObject object = JSONObject.parseObject(data.getData());
//            for (Map.Entry<String,Object> entry:object.entrySet()) {
//
//                pairs.add(Pair.create(entry.getKey(),entry.getValue().toString()));
//            }
//            realTimeAdapter.setData(pairs);
//            realTimeAdapter.notifyDataSetChanged();

//            List<SerialPortDataModel> serialPortData = JSON.parseArray("["+data.getData()+"]", SerialPortDataModel.class);
//            Map<String ,String> serialPortDatas = (Map<String, String>) JSON.parse("["+data.getData()+"]");
//
////            Map<String ,String> serialPortDatas= new HashMap<>();
//
//            realTimeBeanList.clear();
//            realTimeBeanList.addAll(serialPortData);
//            realTimeAdapter.notifyDataSetChanged();
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowMessageEvent(OrderDetailEvent orderDetailEvent) {

//        LogUtils.e("实时数据 : " + orderDetailEvent.getListDetailBean().getActual_production());
    }


    @Override
    public void onResume() {
        super.onResume();
//            initData();
        EventBus.getDefault().register(this);

    }

    private SharedPreferences mPreferences;


    private void initData() {
        LogUtils.e("equip : " + equipmentID);
        String user = SPUtils.getString(getActivity(), "user");
        String key = SPUtils.getString(getActivity(), "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);

        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/userEquipment/realTimeDataOfEquipment")
                .url(endpoint + "/userEquipment/realTimeDataOfEquipment")
                .addParams("pun", user)
                .addParams("pd", digest)
                .addParams("t", timer)
                .addParams("equipmentId", "0123cdca-1008-4dc1-85ff-0d1c81abc199")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.e("设备实时数据失败 ：" + call + " ;错误 ：" + e + "; id :" + id);
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        RealTimeData data = JSON.parseObject(response, RealTimeData.class);
                        if (TextUtils.equals("200", data.getStatusCode())) {
//                            LogUtils.e("设备实时数据成功 : " + response);
//                            List<RealTimeData.DataBean> dataBeanList = data.getData();
//                            realTimeBeanList.addAll(dataBeanList);
//                            realTimeAdapter.notifyDataSetChanged();
                        } else {
                            LogUtils.e("设备实时数据失败 ; ");
                        }

                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    List<Pair<String, Integer>> pairs = new ArrayList<>();

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSocketEvent(SocketEvent event) {
        pairs.clear();
        LogUtils.e("接受到了event");
        if (event.getReturnMap().size() > 0) {
            for (String key : event.getReturnMap().keySet()) {
                Integer value = event.getReturnMap().get(key);
                pairs.add(Pair.create(key, value));
            }
            realTimeAdapter.setData(pairs);
            realTimeAdapter.notifyDataSetChanged();
            tvNodata.setVisibility(View.GONE);
        } else {
            tvNodata.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
